package com.kay.servlet;

import com.kay.annote.Autowired;
import com.kay.factory.BeanFactory;
import com.kay.factory.ProxyFactory;
import com.kay.pojo.Result;
import com.kay.service.TransferService;
import com.kay.service.impl.TransferServiceImpl;
import com.kay.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebServlet(name="transferServlet",urlPatterns = "/transferServlet")
public class TransferServlet extends HttpServlet {


//    private ProxyFactory proxyFactory = (ProxyFactory) BeanFactory.getBean("proxyFactory");
//    // 1. 获取TransferService实例化对象 并通过 ProxyFactory 动态代理类工厂将实例化后的TransferService进行增强
//    private TransferService transferService = (TransferService) proxyFactory.getProxyObject(BeanFactory.getBean("transferService"));

//    public void setTransferService(TransferService transferService) {
//        this.transferService = transferService;
//    }

    private TransferService transferService = (TransferService)BeanFactory.getBean("transferService");

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 设置请求体的字符编码
        req.setCharacterEncoding("UTF-8");

        String fromCardNo = req.getParameter("fromCardNo");
        String toCardNo = req.getParameter("toCardNo");
        String moneyStr = req.getParameter("money");
        int money = Integer.parseInt(moneyStr);

        Result result = new Result();

        try {
            // 2. 调用service层方法
            transferService.transfer(fromCardNo,toCardNo,money);
            result.setStatus("200");
        } catch (Exception e) {
            e.printStackTrace();
            result.setStatus("201");
            result.setMessage(e.toString());
        }

        // 响应
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().print(JsonUtils.object2Json(result));
    }
}
